<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>手写Promise.all</title>

<script type="text/javascript">
	// function pAll (_promises) {
	// return new Promise((resolve, reject) => {
	// 	const promises = Array.from(_promises)
	// 	const r = []
	// 	const len = promises.length
	// 	let count = 0
	// 	for (let i = 0; i < len; i++) {
	// 	Promise.resolve(promises[i]).then(o => {
	// 		r[i] = o
	// 		if (++count === len) {
	// 		resolve(r)
	// 		}
	// 	}).catch(e => reject(e))
	// 	}
	// })
	// }


	// _promises: 代表可迭代的对象，内部元素可以是期约，也可以是非期约

	// function pAll(_promises){
	// 	return new Promise((resolve, reject) => {
	// 		const promises = Array.from(_promises);
	// 		const results = [];
	// 		let count = 0;
	// 		const len = promises.length;
	// 		for(let i = 0; i < len; i ++){
	// 			Promise.resolve(promises[i]).then(res => {
	// 				results[i] = res;
	// 				if(++ count === len){
	// 					resolve(results);
	// 				}
	// 			}).catch(err => reject(err));
	// 		}
	// 	})
	// }

	// const sleep = time => new Promise(resolve => setTimeout(resolve, time))

	// 全部是非期约，期约兑现的测试
	// pAll([1, 2, 3]).then(o => console.log(o))
	// pAll([1, Promise.resolve(3)]).then(o => console.log(o))
	// pAll([1, Promise.reject(3)]).then(o => console.log('done')).catch(e => console.log(e))
	// Promise.all([1, Promise.reject(3)]).then(o => console.log('done')).catch(e => console.log(e))
	// // 并行执行
	// pAll([sleep(2000), sleep(1000), sleep(5000), sleep(1000), sleep(1000)]).then(o => console.log('Sleep Done'))




	function pAll(_promises){
		return new Promise((resolve, reject) => {
			const promises = Array.from(_promises);
			let count = 0;
			const len = promises.length;
			let results = [];

			for(let i = 0; i < len; i ++){
				Promise.resolve(promises[i]).then(res => {
					results[i] = res;
					if(++ count === len) resolve(results);
				}).catch(err => reject(err));
			}
		})
	}

	const sleep = time => new Promise(resolve => setTimeout(resolve, time));

	pAll([1, 2, 3]).then(res => console.log(res));
	pAll([1, Promise.resolve(3)]).then(res => console.log(res));
	pAll([1, Promise.reject(4)]).then(res => console.log('done')).catch(err => console.log(err));

	pAll([sleep(1000), sleep(200), sleep(5000)]).then(res => console.log('sleep done'));




















</script>


</head>
<body>

</body>
</html>